<template>
  <Card :bordered="false" dis-hover class="ivu-mt">
    <div class="i-table-no-border">
      <Button type="primary" icon="md-add" @click="handleOpenCreate"
        >新建</Button
      >
      <Table
        highlight-row
        size="small"
        ref="table"
        :columns="columns"
        :data="list"
        :loading="loading"
        class="ivu-mt"
      >
        <template #status="{ row }">
          <Badge
            status="success"
            :text="row.status_str"
            v-if="row.status === '1'"
          />
          <Badge status="error" :text="row.status_str" v-else />
        </template>
        <template #action="{ row, index }">
          <a @click="handleUpdate(index)">编辑</a>
        </template>
      </Table>
      <div class="ivu-mt">
        <Page
          :total="total"
          :modelValue="current"
          show-total
          show-elevator
          :page-size="size"
          @on-change="handleChangeSize"
          :page-size-opts="pageOpts"
          show-sizer
          @on-page-size-change="changePageSize"
        />
      </div>
      <!--        <div class="ivu-mt ivu-text-center">-->
      <!--            <Page :total="total" :modelValue="current" @on-change="handleChangeSize" />-->
      <!--        </div>-->
      <Modal
        v-model="showCreate"
        :title="title"
        :mask-closable="false"
        :loading="creating"
        :draggable="true"
        @on-ok="handleCreate"
      >
        <Form
          ref="create"
          :model="createMenuData"
          :rules="createRules"
          :label-width="100"
        >
          <FormItem label="菜单名称：" prop="name">
            <Input
              v-model="createMenuData.name"
              placeholder="请输入菜单名称"
              clearable
            />
          </FormItem>
          <FormItem label="父菜单名称：" prop="parent_menu_id">
            <TreeSelect
              v-model="createMenuData.parent_menu_id"
              :data="parentMenuLists"
              v-width="200"
              clearable
            />
          </FormItem>
          <FormItem label="菜单链接：" prop="url">
            <Input
              v-model="createMenuData.url"
              placeholder="请输入菜单链接"
              clearable
            />
          </FormItem>
          <FormItem label="菜单Icon：" prop="class_style">
            <Input
              v-model="createMenuData.class_style"
              placeholder="请输入Icon类名"
              clearable
            />
          </FormItem>
          <FormItem label="排序：" prop="sort">
            <InputNumber
              v-model="createMenuData.sort"
              :min="0"
              placeholder="排序"
            />
          </FormItem>
          <FormItem label="菜单状态：">
            <Switch v-model="createMenuData.status">
              <span slot="open">开启</span>
              <span slot="close">关闭</span>
            </Switch>
          </FormItem>
        </Form>
      </Modal>
    </div>
  </Card>
</template>

<script>
import {
  GetMenus,
  GetParentMenus,
  CreateMenu,
  UpdateMenu,
  ChangeTypeMenu,
} from "@/api/menu.js";

export default {
  data() {
    return {
      columns: [
        {
          title: "菜单名称",
          key: "name",
          minWidth: 100,
        },
        {
          title: "父菜单名称",
          key: "pname",
          minWidth: 100,
        },
        {
          title: "菜单Icon",
          key: "class_style",
          minWidth: 160,
        },
        {
          title: "url路径",
          key: "url",
          minWidth: 140,
        },
        {
          title: "排序",
          key: "sort",
          width: 80,
        },
        {
          title: "状态",
          slot: "status",
          minWidth: 80,
        },
        {
          title: "创建时间",
          key: "created_at_str",
          minWidth: 140,
        },
        {
          title: "操作",
          slot: "action",
          align: "center",
          minWidth: 80,
        },
      ],
      loading: false,
      list: [],
      pageOpts: [10, 20, 30, 50],
      parentMenuList: {},
      parentMenuLists: [],
      current: 1,
      size: 10,
      total: 0,
      showCreate: false,
      createMenuData: {
        name: "",
        module_id: 1,
        url: "",
        parent_menu_id: "",
        class_style: "",
        status: true,
        sort: null,
      },
      createRules: {
        name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
        module_id: [
          { required: true, message: "请选择所属模块", trigger: "change" },
        ],
        url: [{ required: true, message: "请输入菜单连接", trigger: "blur" }],
        class_style: [
          { required: true, message: "请输入菜单Icon", trigger: "blur" },
        ],
        sort: [
          {
            message: "排序必须是正数",
            pattern: /^[+]{0,1}(\d+)$/,
            trigger: "blur",
          },
        ],
        module_id: [{ required: true, message: "请选择模块", trigger: "blur" }],
        status: [
          { required: true, message: "请输入菜单状态", trigger: "blur" },
        ],
      },
      creating: true,
      updateIndex: -1,
      editing: true,
      title: "新增",
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    getData() {
      this.loading = true;
      GetMenus({
        pageSize: this.size,
        page: this.current,
      })
        .then((res) => {
          this.list = res.list;
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取父级菜单
    getParentMenuList(moduleId) {
      GetParentMenus({ id: moduleId }).then((res) => {
        this.parentMenuLists = res.condition.menu;
      });
    },
    // 点击切换分页
    handleChangeSize(currentPage) {
      this.current = currentPage;
      this.getData();
    },
    changePageSize(e) {
      this.size = e;
      this.getData();
    },
    // 切换状态
    handlechangeType(id, type) {
      this.$Modal.confirm({
        title: "警告",
        content: "是否确认" + (type === 1 ? "开启" : "关闭") + "该菜单？",
        onOk: () => {
          ChangeTypeMenu({
            id: id,
            status: type,
          }).then(() => {
            this.getData();
            this.$Message.success("修改成功");
          });
        },
      });
    },
    // 点击新增
    handleOpenCreate() {
      this.updateIndex = -1;
      this.showCreate = true;
      this.title = "新增";
      this.$nextTick(() => {
        this.$refs["create"].resetFields();
      });
      this.getParentMenuList();
    },
    // 新增数据
    handleCreate() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          let sendData = JSON.parse(JSON.stringify(this.createMenuData));
          sendData.status = sendData.status === true ? "1" : "0";
          if (this.updateIndex < 0) {
            // 新建
            CreateMenu(sendData).then((res) => {
              // 创建模块成功后，刷新页面
              this.showCreate = false;
              this.getData();
              this.$Message.success("创建菜单成功");
            });
          } else {
            if (sendData.status == 0) {
              this.$Modal.confirm({
                title: "确认",
                content: "确定停用？操作此动作会解除角色/动作绑定",
                loading: true,
                onOk: () => {
                  UpdateMenu(sendData).then((res) => {
                    this.$Modal.remove();
                    this.showCreate = false;
                    this.getData();
                    this.$Message.success("修改成功");
                  });
                },
              });
            } else {
              // 修改
              UpdateMenu(sendData).then((res) => {
                // 修改模块成功后，刷新页面
                this.showCreate = false;
                this.getData();
                this.$Message.success("修改成功");
              });
            }
          }
          this.creating = false;
          this.$nextTick(() => {
            this.creating = true;
          });
        } else {
          this.creating = false;
          this.$nextTick(() => {
            this.creating = true;
          });
        }
      });
    },
    // 编辑数据
    handleUpdate(index) {
      this.showCreate = true;
      this.title = "编辑";
      this.$nextTick(() => {
        this.$refs["create"].resetFields();
        this.updateIndex = index;
        const item = this.list[index];
        for (let key in this.createMenuData) {
          if (key == "sort") {
            this.createMenuData[key] = +item[key];
          } else {
            this.createMenuData[key] = item[key];
          }
        }
        this.createMenuData.status = this.createMenuData.status === "1";
        this.createMenuData.id = item.id;
        // this.getParentMenuList(item.id, this.createMenuData.module_id);
        //模块都为1
        this.getParentMenuList(this.createMenuData.module_id);
      });
    },
    changemodule(e) {
      this.parentMenuLists = this.parentMenuList[`${e}`];
    },
  },
};
</script>
<style lang="less" scoped>
.jc {
  width: 6px;
  height: 6px;
  border-radius: 8px;
  margin-right: 8px;
}
.success {
  background-color: #4cce4c;
}
.fail {
  background-color: red;
}
/deep/.ivu-badge-status-text {
  font-size: 12px;
}
</style>
